package com.myself.ssoserver.service

import com.myself.common.service.BaseService
import com.myself.ssoserver.dto.SimpleRegisterRequest
import com.myself.ssoserver.entity.Role
import com.myself.ssoserver.entity.User
import com.myself.ssoserver.entity.Users
import com.myself.ssoserver.repository.UserRepository
import com.myself.ssoserver.utils.PasswordUtils
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException

@Service
open class UserService(
    private val repository: UserRepository
) : BaseService<User, Users>(repository) {

    open fun findByUsername(username: String): User? {
        return repository.findByUsername(username)
    }

    @Transactional
    open fun updateLastLogin(userId: Int, ip: String) {
        findById(userId)?.let {
            it.lastLoginIp = ip
            updateOne(it)
        }
    }

    @Transactional
    open fun simpleRegister(request: SimpleRegisterRequest): User {
        // 检查用户名是否存在
        if (existsByUsername(request.username)) {
            throw RuntimeException("用户名已存在")
        }

        // 创建用户实体
        val user = User {
            username = request.username
            password = PasswordUtils.encode(request.password)
            lastLoginIp = null
            isActive = 1
            role = Role { id = 8 }
        }
        repository.addOne(user)
        return user
    }

    private fun existsByUsername(username: String): Boolean {
        return repository.findByUsername(username) != null
    }

    @Throws(IOException::class)
   open fun getCurrentUser(): User {
        val authentication = SecurityContextHolder.getContext().authentication
        return authentication.principal as User
    }
}
